import CryptoJS from './crypto-js.min'
const CRYPTO_USER_KEY = ''
const CRYPTO_ORDER_KEY = '998a87185c7349bb'

export const formatDate = (time, fmt) => {
  if (time === undefined || '') {
    return
  }
  const date = new Date(time)
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      )
    }
  }
  return fmt
}
function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}
export const formatCentMoney = price => {
  if (price === undefined) {
    return '0.00'
  } else {
    var a = (price / 100).toFixed(2)
    return a
  }
}
/**
 * 跳转 防止页面卡死
 */
export const jumpTo = (url, param = {}, needVavigateTo = true) => {
  let pageList = getCurrentPages()
  url = /\?/.test(url) ? url : `${url}?`
  for (let key in param) {
    url += `${key}=${param[key]}&`
  }
  if (param && JSON.stringify(param) != '{}') {
    url = url.substr(0, url.length - 1)
  }

  if (pageList.length < 10 && needVavigateTo) {
    wx.navigateTo({ url: url })
  } else {
    wx.redirectTo({ url: url })
  }
}
export const json2Form = json => {
  var str = []
  for (var p in json) {
    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(json[p]))
  }
  return str.join('&')
}
/*
  * {param} plaintText 加密明文
  * {param} type 加密类型 0 用户密码加密，1订单加密
  * return  str 加密结果
  */

export const encryptString = (plaintext, type) => {
  var plaintText = plaintext
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }
  var cryptojskey = type === 1 ? CRYPTO_ORDER_KEY : CRYPTO_USER_KEY
  var key = CryptoJS.enc.Utf8.parse(cryptojskey)
  var encryptedData = CryptoJS.AES.encrypt(plaintText, key, options)
  var encryptedBase64Str = encryptedData.toString()
  return encryptedBase64Str
}

/*
  * {param} plaintText 解密密文
  * {param} type 解密类型 0 用户密码解密，1 订单解密
  * return  str 解密结果
  */

export const decryptString = (encryptedStr, type) => {
  var encryptedBase64Str = encryptedStr
  var options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }
  var cryptojskey = type === 1 ? CRYPTO_ORDER_KEY : CRYPTO_USER_KEY
  var key = CryptoJS.enc.Utf8.parse(cryptojskey)
  // 解密
  var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, options)
  // 解密后，需要按照Utf8的方式将明文转位字符串
  var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8)
  return decryptedStr
}

// 转为unicode 编码
export const encodeUnicode = str => {
  var res = []
  for (var i = 0; i < str.length; i++) {
    res[i] = ('00' + str.charCodeAt(i).toString(16)).slice(-4)
  }
  return '\\u' + res.join('\\u')
}

// 解码
export const decodeUnicode = str => {
  str = str.replace(/\\/g, '%')
  return unescape(str)
}
// 获取元素
export const onTotalReady = (selector, _this, time = 50, callback) => {
  var query = wx.createSelectorQuery().in(_this)
  let timer = setInterval(() => {
    query
      .select(selector)
      .boundingClientRect(rect => {
        console.log(rect)
        if (rect !== null && timer !== null) {
          clearInterval(timer)
          timer = null
          callback(rect)
        }
      })
      .exec()
  }, time)
}

export let domInter = (value, _this) => {
  return new Promise((resolve, reject) => {
    var query = wx.createSelectorQuery().in(_this)
    query
      .select(value)
      .boundingClientRect(function(res) {
        resolve(res)
      })
      .exec()
  })
}

//获取当前年月日时分秒
export const getNowFormatDate = (time) => {
    if(time){
      var date = new Date(time);
    }else{
      var date = new Date();
    }
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hour = date.getHours()
    var min = date.getMinutes()
    var sec = date.getSeconds()
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if(hour >= 0 && hour <= 9){
      hour = "0"+hour
    }
    if(min >= 0 && min <= 9){
      min = "0"+min
    }
    if(sec >= 0 && sec <= 9){
      sec = "0"+sec
    }
    var counttime = {
      day:strDate,
      hour:hour,
      min:min,
      sec:sec
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + hour + seperator2 + min
            + seperator2 + sec
    if(time){
      return counttime
    }else{
      return currentdate;
    }
    
}

// 数字自动补零
export const addPreZero = num => {
    return ('00000' + num).slice(-6);
}


const chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

export const random =n=> {
  var res = "";
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35);
    res += chars[id];
  }
  return res;
}

//数组去重
export const ArrayToHeavy = (array) => {
  //定义一个新的数组
  var s = [];
  //遍历数组
  for(var i = 0;i<array.length;i++){
      if(s.indexOf(array[i]) == -1){  //判断在s数组中是否存在，不存在则push到s数组中
          s.push(array[i]);
      }
  }
  return s;
}
//保存图片到相册
export const writePhotosAlbum = (successFun,failFun) =>{
  wx.getSetting({
    success(res) {
      if (!res.authSetting['scope.writePhotosAlbum']) {
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
          success: function () {
            successFun && successFun()
          },
          fail: function (res) {
            wx.hideLoading()
            wx.showModal({
              title: '提示',
              content: "小程序需要您的微信授权保存图片，是否重新授权？",
              showCancel: true,
              cancelText: "否",
              confirmText: "是",
              success: function (res2) {
                if (res2.confirm) { //用户点击确定'
                  wx.openSetting({
                    success: (res3) => {
                      if (res3.authSetting['scope.writePhotosAlbum']) {
                        //已授权
                        successFun && successFun()
                      } else {
                        failFun && failFun()
                      }
                    }
                  })
                } else {
                  failFun && failFun()
                }
              }
            });
          }
        })
      } else {
        successFun && successFun()
      }
    }
  })
}



